package br.edu.ufersa.scrumgame.mbean;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import br.edu.ufersa.scrumgame.facade.JogadorFacade;
import br.edu.ufersa.scrumgame.modelo.Jogador;
import br.edu.ufersa.scrumgame.util.Util;

@ManagedBean
@SessionScoped
public class PerfilMBean {

	HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
			.getRequest();
	HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);

	@EJB
	private JogadorFacade jogadorFacade;

	private Jogador usuario = new Jogador();

	public Jogador getUsuario() {

		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (authentication != null && !authentication.getPrincipal().equals("anonymousUser")) {
			usuario = jogadorFacade.findUsuarioByEmail(((User) authentication.getPrincipal()).getUsername());
			Util.createFoto(usuario.getEmail(),usuario.getFoto());
		}

		return usuario;
	}

	public void setUsuario(Jogador usuario) {
		this.usuario = usuario;
	}
	
	public float getPercentExp() {
		float percentual;
		float expMaxNivel = usuario.getNivel().getExperienciaFim();
		
		if( expMaxNivel > 0 ) {
			percentual = (usuario.getExperiencia() / expMaxNivel) * 100;
		} else {
			percentual = 0;
		}
		
		return percentual;
	}

	public float getPercentEner() {
		float percentual;
		float energiaMaxNivel = usuario.getNivel().getMaxEnergia();
		
		if( energiaMaxNivel > 0 ) {
			percentual = (usuario.getEnergia() / energiaMaxNivel) * 100;
		} else {
			percentual = 0;
		}
		
		return percentual;
	}

}
